package com.cy.personer.web.userWeb;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeWapPayRequest;
import com.cy.personer.bean.MoneyDetails;
import com.cy.personer.bean.User;
import com.cy.personer.bean.UserTransaction;
import com.cy.personer.bean.Work;
import com.cy.personer.biz.impl.OperationUserBizImpl;
import com.cy.personer.biz.impl.UserBizImpl;
import com.cy.personer.biz.impl.UserTransactionBizImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping(value = "/userTransaction")
public class UserTransactionHandler {
    @Resource
    private OperationUserBizImpl operationUserBizImpl;
    @Resource
    private UserTransactionBizImpl userTransactionBizImpl;
    @Resource
    private UserBizImpl userBizImpl;

    //展现充值页面
    @RequestMapping(value ="/showUserRecharge.action")
    public String showUserRecharge(HttpServletRequest request,UserTransaction userTransaction){
        String result1 = "";
        String ordeNumber = generateOrdeNumber();
        User frontUser1 = (User) request.getSession().getAttribute("frontUser");
        int userId = frontUser1.getUserId();
        userTransaction.setOrdeNumber(ordeNumber);
        userTransaction.setUserId(userId);
        boolean result = userTransactionBizImpl.addUserTransaction(userTransaction);
        if (result){
            request.setAttribute("ordeNumber",ordeNumber);
            result1 = "user/userRecharge";
        }
        return result1;
    }

    //点击付款按钮
    @RequestMapping(value ="/userRecharge.action")
    public void userRecharge(HttpServletRequest request,HttpServletResponse response, UserTransaction userTransaction) throws AlipayApiException, IOException {

        // 超时时间 可空
        String timeout_express="2m";
        // 销售产品码 必填
        String product_code="QUICK_WAP_WAY";

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = userTransaction.getOrdeNumber();
        //付款金额，必填
        String total_amount = String.valueOf(userTransaction.getOrdeMoney());
        //订单名称，必填
        String subject = "自主充值";
        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式
        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest();

        // 封装请求支付信息
        AlipayTradeWapPayModel model=new AlipayTradeWapPayModel();
        model.setOutTradeNo(out_trade_no);
        model.setSubject(subject);
        model.setTotalAmount(total_amount);
//        model.setBody(body);
        model.setTimeoutExpress(timeout_express);
        model.setProductCode(product_code);
        alipay_request.setBizModel(model);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);

        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单
            form = client.pageExecute(alipay_request).getBody();
            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            response.getWriter().write(form);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }


    //回调页面
    @RequestMapping(value ="/return_url.action")
    public String return_url(HttpServletRequest request,HttpServletResponse resp,User user ) throws IOException, AlipayApiException {
        String result1 = "user/userIndex";
        Map<String,String> params = new HashMap<String,String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号

        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //支付宝交易号

        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2");

        resp.setContentType("text/html; charset=utf-8");
        PrintWriter out = resp.getWriter();
        if(verify_result){//验证成功
            UserTransaction userTransaction = userTransactionBizImpl.findUserTransaction(out_trade_no);
            if (userTransaction != null){
                user.setUserId(userTransaction.getUserId());
                User frontUser1 = userBizImpl.getUser(user);

                MoneyDetails moneyDetails = new MoneyDetails();
                double ordeMoney = Double.parseDouble(request.getParameter("total_amount"));
                double userMoney = ordeMoney+frontUser1.getUserMoney();
                frontUser1.setUserMoney(userMoney);
                //日期
                Date day = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd  HH:mm:ss" );
                String str = sdf.format(day);
                moneyDetails.setMdTime(str);
                moneyDetails.setUserId(frontUser1.getUserId());
                moneyDetails.setWorkId(1);
                moneyDetails.setMoney(ordeMoney);
                moneyDetails.setMatter("自主充值");
                userTransaction.setOrdeName("自主充值");
                userTransaction.setOrdeMoney(ordeMoney);
                userTransactionBizImpl.updataUserTransaction(userTransaction);
                int result = operationUserBizImpl.recharge(frontUser1,moneyDetails);
                if (result ==1){
                    result1 = "redirect:/frontUser/showIndex.action";
//                    resp.sendRedirect(request.getContextPath()+"/index.jsp");
                }else {
                    result1 = "user/userIndex";
                }
            }

        }else {
//            out.println("验签失败");
            result1 = "user/userIndex";

        }

        return result1;

    }

    //查看资金明细
    @RequestMapping(value="/userSeeMoneyDetails.action")
    public String seeMoneyDetails(HttpServletRequest request,String num,MoneyDetails moneyDetails){
        int pageNum = 1;
        if(StringUtils.isNotEmpty(num)){
            if(!num.equals("0")){
                pageNum = Integer.parseInt(num);
            }
        }
        PageHelper.startPage(pageNum,5);
        User user = (User) request.getSession().getAttribute("frontUser");
        moneyDetails.setUserId(user.getUserId());
        List<MoneyDetails> allMoneyDetails = operationUserBizImpl.getMoneyDetails(moneyDetails);
        PageInfo<MoneyDetails> pageInfo = new PageInfo<>(allMoneyDetails);
        request.setAttribute("pageInfo",pageInfo);
        return "user/userMoneyDetails";
    }

    //展示为用户退款页面
    @RequestMapping(value="/showPutForward.action")
    public String showRefund(HttpServletRequest request){
        String result1 = "";
        User frontUser = (User) request.getSession().getAttribute("frontUser");
        User frontUser1 = userBizImpl.getUser(frontUser);
        if (frontUser1.getBankNumbe() != null){
            result1 = "user/userPutForward";
        }else {
            result1 = "user/userAddBank";
        }
        return result1;
    }

    //绑卡时验证持卡人的姓名
    @RequestMapping(value="/userNameCheck.action")
    public @ResponseBody String userNameCheck(HttpServletRequest request,String userName){
        String result1 = "";
        User frontUser = (User) request.getSession().getAttribute("frontUser");
        frontUser.setUserName(userName);
        User frontUser1 = userBizImpl.userNameCheck(frontUser);
        if (frontUser1 != null){
            result1 = "success";
        }else {
            result1 = "error";
        }
        return result1;
    }

    //退款
    @RequestMapping(value="/userRefund.action")
    public String refund(HttpServletRequest request,String userId,MoneyDetails moneyDetails){
        String result1 = "error";
        User user1 = (User) request.getSession().getAttribute("user");
        Work work = (Work) request.getSession().getAttribute("work");
        //日期
        Date day = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd  HH:mm:ss" );
        String str = sdf.format(day);
        moneyDetails.setMdTime(str);

        moneyDetails.setUserId(user1.getUserId());
        moneyDetails.setWorkId(work.getWorkId());
        moneyDetails.setMoney(user1.getUserMoney());
        moneyDetails.setMatter("退款");

        user1.setUserMoney(0);
        int result = operationUserBizImpl.updataUserMoney(user1,moneyDetails);
        if (result ==1){
//            session.setAttribute("user",user1);
            result1 = "redirect:/operationUser/seeMoneyDetails.action";
        }else {
            result1 = "error";
        }
        return result1;

//        result = "redirect:/manageWork/showWork.action";
    }

    //订单号
    public String generateOrdeNumber(){
        int f = UUID.randomUUID().toString().hashCode();
        if (f < 0){//判断是否为负数
            f = -f;
        }
        StringBuilder ordeNumber = new StringBuilder();
        ordeNumber.append("YY");
        ordeNumber.append(String.format("%015d",f));
        return ordeNumber.toString();
    }


}
